package cn.chendd.tips.examples.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;

/**
 * @author chendd
 * @since 2019-08-31 22:15
 * List代理示例，简单的List类方法拦截实现
 */
public class ObjectProxyHandler implements InvocationHandler {

    private static final Logger logger = Logger.getLogger(ObjectProxyHandler.class.getName());

    private Object target;
    private Method method;

    public ObjectProxyHandler(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object object, Method method, Object[] args) throws Throwable {
        this.method = method;
        Object result = null;
        this.before();
        try {
            result = method.invoke(target , args);//方法出错时不执行后置方法
            this.after();
        } catch (Exception e) {
            this.exception(e);
        }
        return result;
    }

    /**
     * 方法前置
     */
    private void before() {
        System.out.println("invoke " + method.getName() + " before");
    }

    /**
     * 方法后置
     */
    private void after(){
        System.out.println("invoke " + method.getName() + " after");
    }

    /**
     * 异常处理
     * @param e
     */
    public void exception(Exception e){
        System.err.println("invoke " + method.getName() + " exception");
    }

}
